package com.example.rabbitmq.producer.direct.service.impl;

import com.example.common.config.RabbitMQConfig;
import com.example.common.model.User;
import com.example.rabbitmq.producer.direct.service.RabbitMQService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * TODO
 *
 * @author chenzhian
 * @version 0.1.0
 * @since 0.1.0
 */
@Service
public class RabbitMQServiceImpl implements RabbitMQService {

  //日期格式化
  private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  @Resource
  private RabbitTemplate rabbitTemplate;

  @Override
  public String sendMsg(String msg) throws Exception {
    try {
      String msgId = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
      String sendTime = sdf.format(new Date());
      Map<String, Object> map = new HashMap<>();
      map.put("msgId", msgId);
      map.put("sendTime", sendTime);
      map.put("msg", msg);
      rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE,
          RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, map);
      return "ok";
    } catch (Exception e) {
      e.printStackTrace();
      return "error";
    }
  }

  @Override
  public void sendObject(User user) {
    System.out.println("Send Object: " + user.toString());
    rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE,
        RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, user);
  }

}
